package com.my.study.zookeeper_study;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * @author zlx
 * @Description 创建结点 create
 * （1）同步创建结点： 需要关注异常
 * （2）异步创建结点： 不需要关注异常，异常通过返回码体现
 *
 * 获取字节点：getChildren
 *
 * 获取节点值：getData
 *
 * 更新节点值：setData
 *
 * 删除结点：delete
 *
 * @Date 2020-08-19
 * @Param
 * @return
 **/
public class MyZookeeperStudy2 implements Watcher{

    private static ZooKeeper zooKeeper = null;
    private static Stat stat = new Stat();

    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) {

        MyZookeeperStudy2 myZookeeperStudy2 = new MyZookeeperStudy2();

        try {
            String connectStr = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183";
            int sessionTimeOut = 5000;
            zooKeeper = new ZooKeeper(connectStr, sessionTimeOut, myZookeeperStudy2);
            countDownLatch.await();
            String path = "/zlx/test2";
            //异步创建 临时结点
            //zooKeeper.create("/zlx/test3", "test3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new MyStringCallBack(), "I am context.");
            //zooKeeper.create("/zlx/test3", "test3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new MyStringCallBack(), "I am context.");
            //zooKeeper.create("/zlx/test3", "test3".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, new MyStringCallBack(), "I am context.");
            //System.out.println("res :=====");

            //同步创建
            String res = zooKeeper.create(path, "My test2 val".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
            //临时结点不能创建子节点
            //zooKeeper.create("/zlx/test2/mytest", "My test2 val".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);

            System.out.println("结点创建结果res is:    " + res);

            List<String> children = zooKeeper.getChildren("/zlx", true);
            System.out.println(children);
            //获取结点值
            //byte[] val = zooKeeper.getData(path, myZookeeperStudy2, stat);
            System.out.println(path + " val is:" + new String(zooKeeper.getData(path, myZookeeperStudy2, stat)));
            System.out.println(stat.getCzxid() +"," + stat.getMzxid() + ", " + stat.getVersion());
            zooKeeper.setData(path, "test2 new val hahah".getBytes(), -1);

            zooKeeper.delete(path, -1);
            Thread.sleep(Integer.MAX_VALUE);
            //System.out.println(path + " val is: " + new String(zooKeeper.getData(path, myZookeeperStudy2, stat)));
        }catch (IOException e){
            e.printStackTrace();
        }catch (KeeperException e){
            e.printStackTrace();
        }catch (InterruptedException e){
            e.printStackTrace();
        }

    }

    @Override
    public void process(WatchedEvent event) {

       try {
           if (event.getState() == Event.KeeperState.SyncConnected) {
               if(Event.EventType.None == event.getType() && null == event.getPath()){
                   System.out.println("======ready--=======");
                   countDownLatch.countDown();
               }
               if (Event.EventType.NodeDataChanged == event.getType()) {
                   System.out.println("------------------------NodeDataChanged new date val is: ====" + new String(zooKeeper.getData(event.getPath(), true, stat)));
                   System.out.println(stat.getCzxid() +"," + stat.getMzxid() + ", " + stat.getVersion());
               }else if(Event.EventType.NodeChildrenChanged == event.getType()) {
                   System.out.println("------------------------NodeChildrenChanged : "+ zooKeeper.getChildren(event.getPath(), true));
               }else if(Event.EventType.NodeCreated == event.getType()){
                   System.out.println("-----------------------NodeCreated :" + event.getPath() + " is new created");
               }else if(Event.EventType.NodeDeleted == event.getType()){
                   System.out.println("-----------------------NodeDeleted: "+ event.getPath());
               }
           }
       }catch (Exception e){
           e.printStackTrace();
       }
    }
}
